//
//  HMRefreshControl.swift
//  weibo10
//
//  Created by mac on 15/10/27.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

let downPushMagin: CGFloat = -60
class HMRefreshControl: UIRefreshControl {
    // MARK: - 重写开启、结束刷新
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimating()
    }

    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimating()
    }
    
    // MARK: - 实现KVO,标识是否旋转
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    
        if frame.origin.y > 0 {
            return
        }
        // 如果正在刷新，开启动画
        if refreshing {
            refreshView.startAnimating()
            return
        }
        
        if frame.origin.y < downPushMagin && !refreshView.isRefresh {
            refreshView.isRefresh = true
            return
        }
        if frame.origin.y > downPushMagin && refreshView.isRefresh {
            refreshView.isRefresh = false
            return
        }
    }
    // MARK: -构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupUI()
    }
    // MARK: - 设置UI
    private func setupUI() {
        /// 添加控件
        addSubview(refreshView)
        /// 布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
             make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refreshView.bounds.size)
        }
        /// KVO - 监听属性的变化
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
             self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
       
    }
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    // 懒加载控件
    private lazy var refreshView = HMRefreshView.refreshView()
}
// MARK: -下拉刷新视图
class HMRefreshView: UIView {
    // 箭头
    @IBOutlet weak var arrawView: UIImageView!
    // 下拉刷新视图
    @IBOutlet weak var downPullView: UIView!
    // 圆圈刷新标志
    @IBOutlet weak var circleView: UIImageView!
    /// 是否刷新标志
    var isRefresh = false {
        didSet {
            // 旋转角度
            var angle = CGFloat(M_PI)
            angle += isRefresh ? -0.00001 : 0.00001
            UIView.animateWithDuration(0.5) { () -> Void in
                self.arrawView.transform = CGAffineTransformRotate(self.arrawView.transform, angle)
            }
        }
    }
    class func refreshView() -> HMRefreshView {
        
        let nib = UINib(nibName: "HMRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil)[0] as! HMRefreshView
    }
    /// 开始动画
    private func startAnimating() {
        downPullView.hidden = true
        let key = "transform.rotation"
        if circleView.layer.animationForKey(key) != nil {
            return
        }
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        anim.removedOnCompletion = false
        
        circleView.layer.addAnimation(anim, forKey: nil)
    }
    /// 停止动画
    private func stopAnimating() {
        downPullView.hidden = false
        // 移除动画
        circleView.layer.removeAllAnimations()
    }
}